package cn.kgc.servlet;

import cn.kgc.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/5/11
 * @Description:
 */
@WebServlet(value = "/user",loadOnStartup = 2)
public class UserServlet extends HttpServlet {

    public UserServlet(){
        System.out.println("==========UserServlet()==========");
    }
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        if("tom".equals(username)&&"123456".equals(password)){
            writer.print("<h1>登录成功</h1>");
            writer.print("<h1>欢迎您"+username+"</h1>");

            // 用户的信息列表
            User user = new User().setId(1).setUsername("tom").setPassword("123456").setAge(20);
            List<User> users = Arrays.asList(user, user, user, user);

            writer.print("<table border=\"1px\" cellspacing=\"0\" width=\"100%\">");
            writer.print("<tr>");
            writer.print("<th>ID</th>");
            writer.print("<th>用户名</th>");
            writer.print("<th>密码</th>");
            writer.print("<th>年龄</th>");
            writer.print("</tr>");

            for (User usr: users) {
                writer.print("<tr>");
                writer.print("<th>"+usr.getId()+"</th>");
                writer.print("<th>"+usr.getUsername()+"</th>");
                writer.print("<th>"+usr.getPassword()+"</th>");
                writer.print("<th>"+usr.getAge()+"</th>");
                writer.print("</tr>");
            }

            writer.print("</table>");
        }else {
            writer.print("<h1>登录失败</h1>");
        }
        writer.close();
    }
}
